package com.ruoyi.merchant.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.db.domain.MerchantDataAllocateInfo;
import com.ruoyi.db.domain.SseEvent;
import com.ruoyi.db.mapper.MerchantDataAllocateInfoMapper;
import com.ruoyi.laiqianba.enums.SseEventType;
import com.ruoyi.laiqianba.manager.SseConnectionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.db.mapper.MerchantDataPushInfoMapper;
import com.ruoyi.db.domain.MerchantDataPushInfo;
import com.ruoyi.merchant.service.IMerchantDataPushInfoService;

import javax.annotation.Resource;

/**
 * 商户推送信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-05
 */
@Service
@DataSource(DataSourceType.SLAVE)
@Slf4j
public class MerchantDataPushInfoServiceImpl implements IMerchantDataPushInfoService {
    @Resource
    private MerchantDataPushInfoMapper merchantDataPushInfoMapper;


    @Autowired
    private MerchantDataAllocateInfoMapper merchantDataAllocateInfoMapper;

    @Autowired
    SseConnectionManager  sseConnectionManager;

    /**
     * 查询商户推送信息
     *
     * @param id 商户推送信息主键
     * @return 商户推送信息
     */
    @Override
    public MerchantDataPushInfo selectMerchantDataPushInfoById(Long id) {
        return merchantDataPushInfoMapper.selectMerchantDataPushInfoById(id);
    }

    /**
     * 查询商户推送信息列表
     *
     * @param merchantDataPushInfo 商户推送信息
     * @return 商户推送信息
     */
    @Override
    public List<MerchantDataPushInfo> selectMerchantDataPushInfoList(MerchantDataPushInfo merchantDataPushInfo) {
        return merchantDataPushInfoMapper.selectMerchantDataPushInfoList(merchantDataPushInfo);
    }

    /**
     * 查询商户推送信息列表
     *
     * @param merchantDataPushInfo 商户推送信息
     * @return 商户推送信息
     */
    @Override
    public List<Map<String, Object>> selectMerchantDataPushInfoMapList(MerchantDataPushInfo merchantDataPushInfo) {
        return merchantDataPushInfoMapper.selectMerchantDataPushInfoMapList(merchantDataPushInfo);
    }

    @Override
    public List<Map<String, Object>> selectMerchantDataPushInfoMapList1(MerchantDataPushInfo merchantDataPushInfo) {
        return merchantDataPushInfoMapper.selectMerchantDataPushInfoMapList1(merchantDataPushInfo);
    }

    @Override
    public List<Map<String, Object>> selectMerchantDataList(MerchantDataPushInfo merchantDataPushInfo) {
        // 原始数据库查询结果
        List<Map<String, Object>> mapList = merchantDataPushInfoMapper.selectMerchantDataList(merchantDataPushInfo);

        // 获取当前时间
        LocalTime currentTime = LocalTime.now();

        List<String> allHours = new ArrayList<>();
        for (int hour = 0; hour <= currentTime.getHour(); hour++) {
            int maxMinute = (hour == currentTime.getHour()) ? currentTime.getMinute() : 59;
            for (int minute = 0; minute <= maxMinute; minute += 10) {
                String hourString = String.format("%02d:%02d:00", hour, minute);
                allHours.add(hourString);
            }
        }
        List<Map<String, Object>> filledMapList = allHours.stream()
                .map(hour -> {
                    Map<String, Object> hourMap = new HashMap<>();
                    hourMap.put("Hour", hour);
                    // 查找当前小时是否在数据库结果中，如果是，则取出对应的 Count；否则设为0
                    Optional<Map<String, Object>> matchingHour = mapList.stream()
                            .filter(map -> map.get("Hour").equals(hour))
                            .findFirst();
                    hourMap.put("Count", matchingHour.map(map -> map.get("Count")).orElse(0));
                    return hourMap;
                })
                .collect(Collectors.toList());

        return filledMapList;
    }

    /**
     * 新增商户推送信息
     *
     * @param merchantDataPushInfo 商户推送信息
     * @return 结果
     */
    @Override
    public int insertMerchantDataPushInfo(MerchantDataPushInfo merchantDataPushInfo) {
        merchantDataPushInfo.setCreateTime(DateUtils.getNowDate());
        return merchantDataPushInfoMapper.insertMerchantDataPushInfo(merchantDataPushInfo);
    }

    /**
     * 修改商户推送信息
     *
     * @param merchantDataPushInfo 商户推送信息
     * @return 结果
     */
    @Override
    public int updateMerchantDataPushInfo(MerchantDataPushInfo merchantDataPushInfo) {
        merchantDataPushInfo.setUpdateTime(DateUtils.getNowDate());
        return merchantDataPushInfoMapper.updateMerchantDataPushInfo(merchantDataPushInfo);
    }

    /**
     * 批量删除商户推送信息
     *
     * @param ids 需要删除的商户推送信息主键
     * @return 结果
     */
    @Override
    public int deleteMerchantDataPushInfoByIds(Long[] ids) {
        return merchantDataPushInfoMapper.deleteMerchantDataPushInfoByIds(ids);
    }

    /**
     * 删除商户推送信息信息
     *
     * @param id 商户推送信息主键
     * @return 结果
     */
    @Override
    public int deleteMerchantDataPushInfoById(Long id) {
        return merchantDataPushInfoMapper.deleteMerchantDataPushInfoById(id);
    }


    @Override
    public int laoquMerchantDataPoolInfo(MerchantDataPushInfo merchantDataPushInfo) {
        Long userId = SecurityUtils.getUserId();
        MerchantDataPushInfo merchantDataPushInfo1 = new MerchantDataPushInfo();
        merchantDataPushInfo1.setDistStatus(1L);
        merchantDataPushInfo1.setId(merchantDataPushInfo.getId());
        merchantDataPushInfo1.setUserId(userId);
        int i = merchantDataPushInfoMapper.updateMerchantDataPushInfo(merchantDataPushInfo1);


        //添加到我的数据
        MerchantDataAllocateInfo merchantDataAllocateInfo = new MerchantDataAllocateInfo();
        merchantDataAllocateInfo.setUid(merchantDataPushInfo.getUid());
        merchantDataAllocateInfo.setType(2l);
        merchantDataAllocateInfo.setUserId(userId);
        merchantDataAllocateInfo.setDateInfo(merchantDataPushInfo.getDateInfo());
        merchantDataAllocateInfo.setInfoId(merchantDataPushInfo.getInfoId());
        merchantDataAllocateInfo.setDeptId(merchantDataPushInfo.getDeptId());
        merchantDataAllocateInfo.setStatus(0l);
        merchantDataAllocateInfo.setCreateTime(DateUtils.getNowDate());

        return merchantDataAllocateInfoMapper.insertMerchantDataAllocateInfo(merchantDataAllocateInfo);

    }

    @Override
    public List<Map<String, Object>> selectApiData(Integer type) {
        LocalDate dateInfo = LocalDate.now();

        if (type == 0 || type == 1) {
            dateInfo = (type == 0) ? dateInfo : dateInfo.minusDays(1); // 今天或者昨天的日期
        } else if (type == 2 || type == 3 || type == 4) {
//            int date = (type == 2) ? 3 : 5; // 根据类型确定要减去的天数
            int date = (type == 2) ? 3 : (type == 4) ? 30 : 5; // 根据类型确定要减去的天数
            LocalDate startDate = dateInfo.minusDays(date); // 开始日期
            LocalDate endDate = LocalDate.now().minusDays(1);
            List<Map<String, Object>> ApiData = merchantDataPushInfoMapper.selectAllApiData(startDate.toString(), endDate.toString());
            return ApiData;
        }
        List<Map<String, Object>> ApiData = merchantDataPushInfoMapper.selectApiData(dateInfo.toString());
        return ApiData;
    }

    @Override
    public List<Map<String, Object>> selectApiData1(String startDate, String endDate) {
        return merchantDataPushInfoMapper.selectApiDataInfo(startDate, endDate);
    }

    @Override
    public Long selectAllApiBcount(String startDate, String endDate) {
        return merchantDataPushInfoMapper.selectAllApiBcount(startDate, endDate);
    }

    @Override
    public int deleteMerchantDataPushInfoByDateInfo(String dateInfo) {
        return merchantDataPushInfoMapper.deleteMerchantDataPushInfoByDateInfo(dateInfo);
    }

    @Override
    public int getRegisterException(JSONObject jsonObject) {
        // 构建推送失败事件数据
        Map<String, Object> eventData = new HashMap<>();
        eventData.put("pushInfoId", jsonObject.getString("InfoId"));
        eventData.put("uid", jsonObject.getString("uid"));
        eventData.put("channelCode", jsonObject.getString("channelCode"));
        eventData.put("merchantName", jsonObject.getString("infoName"));
        eventData.put("errorMessage", jsonObject.getString("msg"));
        SseEvent event = SseEvent.of(
                SseEventType.MERCHANT_PUSH_FAILED.getCode(),
                eventData,
                String.format("商户[%s]推送失败: %s", jsonObject.getString("infoName"), jsonObject.getString("msg"))
        );
        sseConnectionManager.broadcast(event);
        log.info("发送商户推送失败通知: 商户ID:{}, 商户名称={}", jsonObject.getString("InfoId"), jsonObject.getString("infoName"));
        return 1;
    }

}
